<template>
  <div class="login-container">
    <div class="login-box">
      <!-- Logo和标题 -->
      <div class="login-header">
        <div class="login-logo-placeholder">🎯</div>
        <h1 class="login-title">CRM旅游管理系统</h1>
        <p class="login-subtitle">专为中老年旅游客户设计的客户关系管理系统</p>
      </div>

      <!-- 登录表单 -->
      <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              size="large"
              prefix-icon="User"
              clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              prefix-icon="Lock"
              show-password
              @keyup.enter="handleLogin"
          />
        </el-form-item>

        <!-- 验证码组件 -->
        <AppleCaptcha
            v-model="loginForm.captcha_code"
            v-model:session-id="loginForm.session_id"
            @submit="handleLogin"
            ref="captchaRef"
        />


        <el-form-item>
          <el-button
              type="primary"
              size="large"
              :loading="loading"
              @click="handleLogin"
              class="login-button"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 其他操作 -->
      <div class="login-footer">
        <el-link type="primary" @click="showForgotPassword">
          忘记密码？
        </el-link>
      </div>
    </div>

    <!-- 背景装饰 -->
    <div class="login-bg">
      <div class="bg-circle circle-1"></div>
      <div class="bg-circle circle-2"></div>
      <div class="bg-circle circle-3"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import type {FormInstance, FormRules} from 'element-plus'
import {useAuthStore} from '@/stores/auth'
import type {LoginForm} from '@/types/auth'
import {AppleCaptcha} from '@/components/ui'

const router = useRouter()
const authStore = useAuthStore()

// 表单引用
const loginFormRef = ref<FormInstance>()
const captchaRef = ref()

// 加载状态
const loading = ref(false)

// 登录表单
const loginForm = reactive<LoginForm>({
  username: '',
  password: '',
  captcha_code: '',
  session_id: ''
})

// 表单验证规则
const loginRules: FormRules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur'}
  ]
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    // 1. 验证基础表单
    const valid = await loginFormRef.value.validate()
    if (!valid) return

    // 2. 验证验证码
    if (!loginForm.captcha_code) {
      ElMessage.error('请输入验证码')
      return
    }
    if (!loginForm.session_id) {
      ElMessage.error('验证码会话无效，请刷新验证码')
      return
    }

    loading.value = true

    // 3. 尝试登录
    const success = await authStore.login(loginForm)

    if (success) {
      // 登录成功，跳转到首页
      await router.push('/')
    } else {
      // 登录失败，重新生成验证码
      if (captchaRef.value) {
        captchaRef.value.refresh()
      }
      loginForm.captcha_code = ''
    }
  } catch (error: any) {
    console.error('登录失败:', error)

    // 登录失败时自动重新生成验证码
    if (captchaRef.value) {
      captchaRef.value.refresh()
    }
    // 清空验证码输入
    loginForm.captcha_code = ''
  } finally {
    loading.value = false
  }
}

// 显示忘记密码对话框
const showForgotPassword = () => {
  ElMessageBox.prompt('请输入您的邮箱地址', '重置密码', {
    confirmButtonText: '发送重置链接',
    cancelButtonText: '取消',
    inputPattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
    inputErrorMessage: '请输入正确的邮箱地址'
  }).then(({value}) => {
    ElMessage.success('重置密码链接已发送到您的邮箱')
    // TODO: 调用重置密码API
  }).catch(() => {
    // 用户取消了操作
  })
}
</script>

<style scoped>
.login-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
}

.login-box {
  position: relative;
  width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  z-index: 2;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-logo-placeholder {
  width: 64px;
  height: 64px;
  margin-bottom: 16px;
  font-size: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 16px auto;
}

.login-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
}

.login-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
  line-height: 1.4;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  margin-top: 24px;
}

.login-footer {
  text-align: center;
  margin-top: 20px;
}

.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 1;
}

.bg-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.circle-1 {
  width: 200px;
  height: 200px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.circle-2 {
  width: 150px;
  height: 150px;
  top: 60%;
  right: 10%;
  animation-delay: 2s;
}

.circle-3 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-box {
    width: 90%;
    padding: 30px 20px;
  }

  .login-title {
    font-size: 20px;
  }

  .login-subtitle {
    font-size: 12px;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .login-box {
    background: rgba(30, 30, 30, 0.95);
  }

  .login-title {
    color: #fff;
  }

  .login-subtitle {
    color: #ccc;
  }
}
</style>